<template>
  <el-dialog :title="title" :visible.sync="dialogShow" @close="closeDialog">
    <!-- ! 绘制表单 -->
    <el-form :model="formData" :rules="formRules" ref="form" label-width="160px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:440px;"></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:440px;"></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select @focus="getEmployeeData" v-model="formData.manager" style="width:440px;" placeholder="请选择">
          <!--label字段指定是显示的文字字段； value字段指的将那个字段的数据给v-model绑定的变量 -->
          <el-option v-for="(item,index) in managerList" :key="index" :label="item.username" :value="item.username">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:440px;" rows="3" type="textarea"></el-input>
      </el-form-item>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="btnOk">确定</el-button>
        <el-button size="small" @click="dialogShow=false">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>
import { getDepartmentInfoApi, getDepartmentListApi, addDepartmentApi, editDepartmentApi } from '@/api/department';
import { getEmployeeSimpleApi } from '@/api/employees'
export default {
  name: 'AddDept',
  data() {
    // 部门名称的校验
    const checkNameRepeat = async (valid, value, cb) => {
      // 1. 找到所有部门名称
      let { depts } = await getDepartmentListApi()
      // 2. 找到当前部门的兄弟部门
      let arr = depts.filter(item => item.pid === this.formData.pid)
      // 如果是编辑状态下，还要排除自己
      if (this.formData.id) {
        arr = arr.filter(item => item.id !== this.formData.id)
      }
      // 3. 名称查重了
      const isRepeat = arr.some(item => item.name === value)
      isRepeat ? cb(new Error('名称重复了')) : cb()
    }
    // 部门编码校验
    const checkCodeRepeat = async (valid, value, cb) => {
      // 1. 找到所有部门名称
      let { depts } = await getDepartmentListApi()
      // 如果是编辑状态下，还要排除自己
      if (this.formData.id) {
        depts = depts.filter(item => item.id !== this.formData.id)
      }
      // 2. 名称查重了
      const isRepeat = depts.some(item => item.code === value)
      isRepeat ? cb(new Error('编码重复了')) : cb()
    }

    return {
      // 弹框控制变量
      dialogShow: false,
      // 表单数据变量
      formData: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      // 表单验证规则
      formRules: {
        code: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: checkCodeRepeat, trigger: 'blur' },
        ],
        introduce: [{ required: true, message: '请输入', trigger: 'blur' }],
        manager: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: checkNameRepeat, trigger: 'blur' },
        ],
      },
      // 负责人数据
      managerList: []
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改' : '新增'
    }
  },
  methods: {
    // 获取负责人数据
    async getEmployeeData() {
      this.managerList = await getEmployeeSimpleApi()
    },
    // 提交事件逻辑
    async btnOk() {
      // 1. 表单数据校验
      //   console.log(this.$refs.form); // 获取到el-form组件实例
      //   this.$refs.form.validate((valid) => {
      //     console.log(valid);  // valid 布尔值，表示校验是否通过
      //   })
      try {
        await this.$refs.form.validate()
      } catch (error) {
        return console.log(error)
      }
      // 2. 发生请求
      // 3. 提示成功
      if (this.formData.id) {
        await editDepartmentApi(this.formData)
        this.$message.success('修改成功')
      } else {
        await addDepartmentApi(this.formData)
        this.$message.success('添加成功')
      }
      // 4. 更新列表
      this.$emit('updateList')
      // 5. 关闭弹框，重置表单
      this.dialogShow = false
    },
    // 关闭弹框
    closeDialog() {
      // 重置表单的逻辑写在这里呢
      this.formData = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
      // 移除校验  
      this.$refs.form.clearValidate()
    },
    // 获取回显的数据
    async getFormDataInfo(ID) {
      // 请求数据
      let res = await getDepartmentInfoApi(ID)
      // 回显表单
      this.formData = res
      // 弹框打开
      this.dialogShow = true
    }
  },
}
</script>
<style>
</style>